package ca.cbc.msb.console.bean;

import java.io.IOException;
import java.io.Serializable;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import ca.cbc.msb.console.util.FacesMessageUtil;

@Controller
@Scope("session")
public class SessionBean implements Serializable {
	private static final long serialVersionUID = -4406972699026543231L;
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	private boolean hasWelcomed = false;
	
	@PostConstruct
	public void init() {
		logger.debug("^^^^^^^^^^^^^SessionBean PostConstruct!");
	}
	
    public void idleListener() {
        FacesMessageUtil.instance.addMessage(FacesMessage.SEVERITY_WARN, 
        		"Your session is closed!", "You have been idle for some time.");
        invalidateSession();
    }
    
    public void welcome() {
    	if(hasWelcomed) return;
    	hasWelcomed = true;
    	String userName = getUserName();
        FacesMessageUtil.instance.addMessage(FacesMessage.SEVERITY_INFO, 
        		"Hi " + userName + ", welcome to MSB Console!", null);
        logger.info("-------User {} login-------.", userName);
    }
    
    private String getUserName() {
    	return FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal().getName();
    }
    
    private void invalidateSession() {
    	FacesContext.getCurrentInstance().getExternalContext().invalidateSession();
    }
    
    public void logout() {
    	invalidateSession();
    	logger.info("=======User {} logout=======", getUserName());
    	try {
			FacesContext.getCurrentInstance().getExternalContext().redirect("/msbconsole/");
		} catch (IOException e) {
			logger.error("Error when logout!", e);
		}
    }
}
